/**
 * 用户信息插件
 * 提供指令来查看用户的个人信息
 */
import plugin from '../../../lib/plugins/plugin.js'
import api from '../core/api.js'
import favorLevel from '../core/favorLevel.js'
import levelSystem from '../core/levelSystem.js'
import menuManager from '../../systemDB/menu/menu.js'
import { segment } from 'oicq'

/**
 * 用户信息卡片生成器
 * 负责生成美观的用户信息HTML卡片
 */
class UserInfoCardGenerator {
  /**
   * 计算进度百分比
   * @param {number} current - 当前值
   * @param {number} maxLevel - 最大等级
   * @param {number} currentLevel - 当前等级
   * @param {number} nextLevelValue - 下一级所需值
   * @returns {number} 进度百分比
   */
  static calculateProgress(current, maxLevel, currentLevel, nextLevelValue) {
    if (currentLevel >= maxLevel) return 100;
    return Math.round((current / nextLevelValue) * 100);
  }

  /**
   * 生成用户信息HTML
   * @param {Object} data - 用户信息数据
   * @returns {string} HTML字符串
   */
  static generateHTML(data) {
    // 生成道具列表HTML
    const renderItems = () => {
      if (data.items && data.items.length > 0) {
        return data.items.map(item => `
          <div class="item">${item.name} × ${item.count}</div>
        `).join('');
      }
      return '<div class="no-item">无道具</div>';
    };

    return `
      <!DOCTYPE html>
      <html lang="zh-CN">
      <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>用户信息</title>
        <style>
          /* 全局样式 */
          * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: 'Microsoft YaHei', 'Arial', sans-serif;
          }

          body {
            background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
            min-height: 100vh;
            display: flex;
            justify-content: center;
            align-items: center;
            padding: 20px;
          }

          /* 卡片容器 */
          .card-container {
            perspective: 1000px;
          }

          .card {
            background: white;
            border-radius: 20px;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.15);
            width: 400px;
            overflow: hidden;
            transform-style: preserve-3d;
            transition: transform 0.5s ease;
          }

          .card:hover {
            transform: translateY(-5px);
          }

          /* 卡片头部 */
          .card-header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 25px;
            text-align: center;
            position: relative;
          }

          .avatar-placeholder {
            width: 100px;
            height: 100px;
            background: rgba(255, 255, 255, 0.2);
            border-radius: 50%;
            margin: 0 auto 15px;
            display: flex;
            justify-content: center;
            align-items: center;
            font-size: 36px;
            border: 3px solid rgba(255, 255, 255, 0.3);
          }

          .card-title {
            font-size: 24px;
            margin-bottom: 5px;
            text-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
          }

          .card-subtitle {
            font-size: 14px;
            opacity: 0.9;
          }

          /* 卡片内容 */
          .card-body {
            padding: 25px;
          }

          .info-grid {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 15px;
            margin-bottom: 20px;
          }

          .info-item {
            background: #f8f9fa;
            border-radius: 10px;
            padding: 15px;
            transition: transform 0.3s ease, box-shadow 0.3s ease;
          }

          .info-item:hover {
            transform: translateY(-3px);
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
          }

          .info-label {
            font-size: 13px;
            color: #6c757d;
            margin-bottom: 8px;
            display: block;
          }

          .info-value {
            font-size: 18px;
            font-weight: bold;
            color: #343a40;
          }

          /* 进度条 */
          .progress-section {
            margin-bottom: 25px;
          }

          .progress-title {
            font-size: 16px;
            font-weight: bold;
            color: #343a40;
            margin-bottom: 10px;
            display: flex;
            justify-content: space-between;
            align-items: center;
          }

          .level-badge {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            font-size: 12px;
            padding: 3px 8px;
            border-radius: 12px;
          }

          .progress-container {
            width: 100%;
            height: 12px;
            background: #e9ecef;
            border-radius: 6px;
            overflow: hidden;
            position: relative;
          }

          .progress-bar {
            height: 100%;
            border-radius: 6px;
            background: linear-gradient(90deg, #4a90e2 0%, #50c878 100%);
            transition: width 1s ease-in-out;
          }

          .progress-text {
            font-size: 12px;
            color: #6c757d;
            margin-top: 5px;
            text-align: right;
          }

          /* 道具栏 */
          .items-section {
            margin-top: 20px;
          }

          .items-title {
            font-size: 16px;
            font-weight: bold;
            color: #343a40;
            margin-bottom: 10px;
          }

          .items-container {
            background: #f8f9fa;
            border-radius: 10px;
            padding: 15px;
            max-height: 100px;
            overflow-y: auto;
          }

          .item {
            padding: 5px 0;
            border-bottom: 1px solid #e9ecef;
            display: flex;
            justify-content: space-between;
          }

          .item:last-child {
            border-bottom: none;
          }

          .no-item {
            color: #6c757d;
            text-align: center;
            padding: 10px;
          }

          /* 底部装饰 */
          .card-footer {
            height: 10px;
            background: linear-gradient(90deg, #667eea 0%, #764ba2 100%);
          }
        </style>
      </head>
      <body>
        <div class="card-container">
          <div class="card">
            <div class="card-header">
              <div class="avatar-placeholder">
                <span>U</span>
              </div>
              <h2 class="card-title">用户信息</h2>
              <p class="card-subtitle">ID: ${data.userId}</p><p class="card-subtitle">UID: ${data.uid || '未设置'}</p>
            </div>
            <div class="card-body">
              <div class="info-grid">

                <div class="info-item">
                  <span class="info-label">金币数量</span>
                  <span class="info-value">${data.gold || 0}</span>
                </div>
                <div class="info-item">
                  <span class="info-label">道具数量</span>
                  <span class="info-value">${data.itemCount || 0}</span>
                </div>
                <div class="info-item">
                  <span class="info-label">权限等级</span>
                  <span class="info-value">${data.permission || 0}</span>
                </div>
                <div class="info-item">
                  <span class="info-label">用户等级</span>
                  <span class="info-value">${data.levelInfo.level}/${data.levelInfo.maxLevel}</span>
                </div>
                <div class="info-item">
                  <span class="info-label">好感等级</span>
                  <span class="info-value">${data.favorInfo.level}/${data.favorInfo.maxLevel}</span>
                </div>
              </div>

              <div class="progress-section">
                <div class="progress-title">
                  好感度经验
                  <span class="level-badge">${data.favorInfo.level}</span>
                </div>
                <div class="progress-container">
                  <div class="progress-bar" style="width: ${data.favorProgress}%"></div>
                </div>
                <div class="progress-text">
                  ${data.favorInfo.experience}/${data.favorInfo.nextLevelExperience || data.favorInfo.experience} (${data.favorProgress}%)
                </div>
              </div>

              <div class="progress-section">
                <div class="progress-title">
                  用户等级经验
                  <span class="level-badge">${data.levelInfo.level}</span>
                </div>
                <div class="progress-container">
                  <div class="progress-bar" style="width: ${data.levelProgress}%"></div>
                </div>
                <div class="progress-text">
                  ${data.levelInfo.experience}/${data.levelInfo.nextLevelExperience || data.levelInfo.experience} (${data.levelProgress}%)
                </div>
              </div>

              <div class="items-section">
                <h3 class="items-title">道具列表</h3>
                <div class="items-container">
                  ${renderItems()}
                </div>
              </div>
            </div>
            <div class="card-footer"></div>
          </div>
        </div>
      </body>
      </html>`;
  }
}



export class UserInfo extends plugin {
  constructor() {
    super({
      name: '用户信息',
      dsc: '查看用户的个人信息',
      event: 'message',
      priority: 5000,
      rule: [
        {
          reg: '^(?:#|/)?我的信息$', // 查看用户信息指令
          fnc: 'viewUserInfo'
        }
      ]
    })
  }

  // 初始化插件
  async init() {
    // 注册到菜单
    await this.registerToMenu()
  }

  /**
   * 注册到系统菜单
   * @returns {Promise<void>}
   */
  async registerToMenu() {
    const pluginInfo = {
      name: '用户信息',
      dsc: '查看用户的个人信息',
      cmds: ['#我的信息']
    }
    await menuManager.registerPluginMenu(pluginInfo)
  }

  /**
   * 查看用户信息指令
   * @param {Object} e - 消息事件对象
   * @returns {Promise<void>}
   */
  async viewUserInfo(e) {
    const userId = e.user_id

    try {
      // 获取用户信息和等级上限
      const [
        uid,
        gold,
        items,
        permission,
        favorInfo,
        levelInfo,
        favorMaxLevel,
        levelMaxLevel
      ] = await Promise.all([
        api.getUserUID(userId),
        api.getUserGold(userId),
        api.getUserItems(userId),
        api.getUserPermission(userId),
        favorLevel.getUserFavorLevelInfo(userId),
        levelSystem.getUserLevelInfo(userId),
        favorLevel.getMaxLevel(),
        levelSystem.getMaxLevel()
      ])

      // 补充等级上限信息
      favorInfo.maxLevel = favorMaxLevel;
      levelInfo.maxLevel = levelMaxLevel;

      // 计算好感度进度条
      const favorProgress = UserInfoCardGenerator.calculateProgress(
        favorInfo.experience,
        favorInfo.maxLevel,
        favorInfo.level,
        favorInfo.nextLevelExperience
      );

      // 计算等级进度条
      const levelProgress = UserInfoCardGenerator.calculateProgress(
        levelInfo.experience,
        levelInfo.maxLevel,
        levelInfo.level,
        levelInfo.nextLevelExperience
      );

      // 生成HTML
      const html = UserInfoCardGenerator.generateHTML({
        userId,
        uid,
        gold,
        items,
        itemCount: items.length,
        permission,
        favorInfo,
        favorProgress,
        levelInfo,
        levelProgress
      })

      // 使用menuManager的htmlToImage方法生成图片
      const imageBuffer = await menuManager.htmlToImage(html)

      // 发送图片
      await e.reply([segment.image(imageBuffer)])
    } catch (error) {
      console.error('查看用户信息失败:', error)
      await e.reply('获取用户信息失败，请稍后重试')
    }
  }

  /**
   * 生成用户信息HTML
   * @param {Object} data - 用户信息数据
   * @returns {string} HTML字符串
   * @deprecated 使用UserInfoCardGenerator.generateHTML代替
   */
  generateUserInfoHTML(data) {
    // 保留旧方法以兼容可能的调用，但建议使用新的生成器
    return UserInfoCardGenerator.generateHTML(data);
  }
}